package com.alibaba.citrus.ots.application.report.ability.facade.service;

import com.alibaba.citrus.ots.application.report.ability.repository.PlatformRepository;
import com.alibaba.cz.base.model.store.enums.CargoZoneTypeEnum;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineBatchQueryPlatforms2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByOutCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByOutCodes2Response;
import com.epoch.app.bcorder.model.dto.ListPlatformPageReportRequest;
import com.epoch.app.bcorder.model.dto.ListPlatformPageReportResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.PlatformSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.otsapplicationreportsdk.contants.OtsApplicationReportSdkConstants;
import com.epoch.app.otsapplicationreportsdk.getplatformselectreport.dto.GetPlatformSelectReportRequest;
import com.epoch.app.otsapplicationreportsdk.getplatformselectreport.dto.GetPlatformSelectReportResponse;
import com.epoch.app.otsapplicationreportsdk.getplatformselectreport.service.GetPlatformSelectReportService;
import com.epoch.app.crunifiedinventory.model.dto.OuiWareshouseIndexRequest;
import com.epoch.app.crunifiedinventory.ouiwarehouse.model.OuiWarehouse;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class GetPlatformSelectReportServiceImpl implements GetPlatformSelectReportService {
    private static Log log = Log.getLogger(GetPlatformSelectReportServiceImpl.class);
    @Resource
    BaseDataService baseDataService;

    @Resource
    private BcOrderService bcOtsService;

    @Resource
    private CrUnifiedInventoryService otsUnifiedInventoryService;

    @Resource
    private PlatformRepository platformRepository;

    @Override
    public GetPlatformSelectReportResponse getPlatformSelectReport(GetPlatformSelectReportRequest getPlatformSelectReportRequest) {
        // 查询 所有电商平台 不分页 在前端模糊查询
//        BaselineBatchQueryPlatforms2Request request = BaselineBatchQueryPlatforms2Request.builder()
//                .platformIds(new ArrayList(platformRepository.getWarehouseByPlatFormCodes())).build();

        BaselineBatchQueryPlatforms2Request request = new BaselineBatchQueryPlatforms2Request();
        if (StringUtils.isEmpty(getPlatformSelectReportRequest.getQuery())) {
            ListPlatformPageReportRequest queryRequest = ListPlatformPageReportRequest.builder()
                    .start(0)
                    .limit(500)
                    .build();
            ListPlatformPageReportResponse response = bcOtsService.listPlatformPageReport(queryRequest);
            List<String> allPlatFormIds = new ArrayList();
            if (!ObjectUtils.isEmpty(response) && !CollectionUtils.isEmpty(response.getResult())) {
                response.getResult().forEach(o -> {
                    Map map = (Map) o;
                    String platformCode = (String) map.get("platformCode");
                    if (StringUtil.isNotEmpty(platformCode) && platformCode.length()>2 && "SK".equals(platformCode.substring(0,2)) && !"SK23".equals(platformCode)) {
                        allPlatFormIds.add((String)map.get("platformId"));
                    }
                });
            }
            request.setPlatformIds(allPlatFormIds);
        }else{
            request.setPlatformNames(Arrays.asList(getPlatformSelectReportRequest.getQuery()));
        }

        Result<List<PlatformSDO>> listResult = baseDataService.baselineBatchQueryPlatforms2(request);
        if (ObjectUtils.isEmpty(listResult.getResult())) {
            return GetPlatformSelectReportResponse.builder().total(0).success(false).build();
        }
        List<PlatformSDO> platformSDOS = new ArrayList<>();
        listResult.getResult().forEach(o -> {
            String platformCode = o.getPlatformCode();
            if (StringUtil.isNotEmpty(platformCode) && platformCode.length()>2 && "SK".equals(platformCode.substring(0,2)) && !"SK23".equals(platformCode)) {
                platformSDOS.add(o);
            }
        });

        // 最终前台页面返回数据
        List result = new ArrayList();
        // 组装数据
        platformSDOS.forEach(platformSDO -> {
            result.add(new HashMap<String, String>(){{
                put("label", platformSDO.getPlatformName());
                put("value", platformSDO.getPlatformId());
            }});
        });
        // 加其他电商平台
        boolean queryOtherName = !StringUtils.isEmpty(getPlatformSelectReportRequest.getQuery())
                && (OtsApplicationReportSdkConstants.OTHER_PLATFORM_NAME().indexOf(getPlatformSelectReportRequest.getQuery()) != -1);
        if (StringUtils.isEmpty(getPlatformSelectReportRequest.getQuery()) || queryOtherName) {
            result.add(new HashMap<String, String>(){{
                put("label", OtsApplicationReportSdkConstants.OTHER_PLATFORM_NAME());
                put("value", OtsApplicationReportSdkConstants.OTHER_PLATFORM_ID());
            }});
        }

        return GetPlatformSelectReportResponse.builder().result(result).total(result.size()).success(listResult.isSuccess()).build();
    }

    /**
     * 查询 所有电商平台
     * @return
     */
    private Set<String> getWarehouseByPlatFormCodes() {

        // 查询 1171 的组织id
        OrganizationSDO organizationSDO = allocateOrderByCode("1171");
        if (ObjectUtils.isEmpty(organizationSDO)) {
            return new HashSet<>();
        }

        int start = 0;
        int limit = 500;
        OuiWareshouseIndexRequest wareshouseIndexRequest = OuiWareshouseIndexRequest.builder()
                .start(start)
                .limit(limit)
                .type(CargoZoneTypeEnum.SHARE_CARGOZONE.getType())
                .saleOrgId(organizationSDO.getId()).build();
        Result<List<OuiWarehouse>> ouiWarehouseListResult = otsUnifiedInventoryService.ouiWareshouseIndex(wareshouseIndexRequest);
        int allPage = (int)Math.ceil((double)ouiWarehouseListResult.getTotal() / limit);
        if (ObjectUtils.isEmpty(ouiWarehouseListResult)) {
            log.info("查询电商下仓库为空，入参：{}", JSON.toJSONString(wareshouseIndexRequest));
            return null;
        }
        List<OuiWarehouse> warehouseList = ouiWarehouseListResult.getResult();
        if (CollectionUtils.isEmpty(warehouseList)) {
            log.info("查询电商下仓库为空，入参：{}", JSON.toJSONString(wareshouseIndexRequest));
            return null;
        }
        for (int i = 1; i < allPage; i++) {
            start = limit * i;
            wareshouseIndexRequest.setStart(start);
            Result<List<OuiWarehouse>> ouiWarehouseListResult1 = otsUnifiedInventoryService.ouiWareshouseIndex(wareshouseIndexRequest);
            if (!ObjectUtils.isEmpty(ouiWarehouseListResult1) && !CollectionUtils.isEmpty(ouiWarehouseListResult1.getResult())) {
                warehouseList.addAll(ouiWarehouseListResult1.getResult());
            }
        }

        return warehouseList.stream().map(OuiWarehouse::getEcPlatform).collect(Collectors.toSet());
    }

    /**
     * 根据 code 查询 组织
     * @param code
     * @return
     */
    public OrganizationSDO allocateOrderByCode(String code) {
        BaselineGetOrganizationByOutCodes2Request request = BaselineGetOrganizationByOutCodes2Request.builder().outCodes(Arrays.asList(code)).build();
        BaselineGetOrganizationByOutCodes2Response res =
                baseDataService.baselineGetOrganizationByOutCodes2(request);
        if (ObjectUtils.isEmpty(res)) {
            return null;
        }
        List<OrganizationSDO> result = res.getResult();
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.get(0);
    }

}
